#include "shortcutsettings.hxx"
#include "ui_shortcutsettings.h"
#include "shortcuts.hxx"

#include <QtGui/QMessageBox.h>
#include <QtGui/QKeyEvent>

ShortCutSettings::ShortCutSettings(QWidget* parent) :
	QWidget(parent),
	m_ui(new Ui::ShortCutSettings)
{
	m_ui->setupUi(this);
	initShortcuts();
}

ShortCutSettings::~ShortCutSettings()
{
	delete m_ui;
}

void ShortCutSettings::changeEvent(QEvent* e)
{
	QWidget::changeEvent(e);
	switch(e->type())
	{
		case QEvent::LanguageChange:
			m_ui->retranslateUi(this);
			break;
		default:
			break;
	}
}

void ShortCutSettings::initShortcuts()
{
	Part0 = "";
	Part1 = "";
	Part2 = "";
	Part3 = "";
	keyCode = 0;
	
	m_ui->shortcutLabel->setText("");
	
	shortcutModel = new QStandardItemModel(0, 3, this);
	reloadShortcuts();
	m_ui->shortcutList->setModel(shortcutModel);
	m_ui->shortcutList->setShowGrid(false);
	m_ui->shortcutList->setSelectionBehavior(QAbstractItemView::SelectRows);
	m_ui->shortcutList->setSelectionMode(QAbstractItemView::SingleSelection);
	m_ui->shortcutList->resizeColumnsToContents();
	m_ui->shortcutList->resizeRowsToContents();
	m_ui->shortcutList->setSortingEnabled(false);
	
	connect(m_ui->clearButton, SIGNAL(clicked()), this, SLOT(slotClearShortcut()));
	connect(m_ui->changeButton, SIGNAL(clicked()), this, SLOT(slotChangeShortcut()));
	connect(m_ui->shortcutList, SIGNAM(clicked(const QModelIndex&)), this, SLOT(slotActionSelected(const QModelIndex&)));
}

void ShortCutSettings::slotChangeShortcut()
{
	if (m_ui->changeButton->isChecked())
	{
		keyCode = 0;
		Part0 = "";
		Part1 = "";
		Part2 = "";
		Part3 = "";
		Part4 = "";
		grabKeyboard();
	}
	else
		releaseKeyboard();
}

void ShortCutSettings::slotClearShortcut()
{
	QModelIndex index = m_ui->shortcutList->currentIndex();
	if (!index.isValid())
		return;
		
	int row = index.row();
	QStandardItem* item = shortcutModel->item(row, 2);
	QString iText = item->text();
	
	if (QMessageBox::question(this, tr("Reset Shortcut"),
							"<qt>" + tr("You are going to reset ", "to it's default value.") +
							QString("<br/><b>%1</b>.<br/>").arg(iText) +
							tr("Are you sure you want to do this?") + "</qt>",
							QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
	{
		Shortcuts::getInstance()->clearShortcut(iText);
		m_ui->shortcutLabel->clear();
		reloadShortcuts();
		setSelected(iText);
	}
}


